#-------------------------------------------------------------------------------
# Name:        DBPediaProcess
# Purpose:     Get information of the wikipedia using DBPedia
#
# Author:      Sung Eun Kim
#
# Created:     11/26/2011
# Copyright:   (c) Kim 2011
#-------------------------------------------------------------------------------
#!/usr/bin/env python

import sys
from SPARQLWrapper import SPARQLWrapper, JSON

def getSubjectFromPage(page):
    #Remove all unnecessary strings
    page = page.strip(">")
    page = page.strip("<")
    pages = page.split("/")
    subject = pages[len(pages) - 1]

    #Make it lower so it is case-insensitive
    return subject.lower()

def parseRedirect(redirectFile):
    titles = {}
    fp = open(redirectFile, "r")
    line = "start"
    while (line <> ""):
        line = fp.readline()
        if (line == ""):
            break

        #Tokenize with space
        tokens = line.split(" ")

        #Make sure that the line format is correct
        token_count = len(tokens)
        if (token_count < 3):
            print "ERROR: the following line didn't have the correct format"
            print line
            answer = raw_input("continue?")
            if (answer.lower.find('y') >= 0):
                continue
            else:
                sys.exit(1)

        #Get the title
        subjectPage = tokens[0]
        subject = getSubjectFromPage(subjectPage)
        redirectPage = tokens[2]
        titles[subject] = redirectPage
    fp.close()
    return titles

def parseTitle(titleFile):
    titles = {}
    fp = open(titleFile, "r")
    line = "start"
    while (line <> ""):
        line = fp.readline()
        if (line == ""):
            break

        #Tokenize with space
        tokens = line.split(" ")

        #Make sure that the line format is correct
        token_count = len(tokens)
        if (token_count < 3):
            print "ERROR: the following line didn't have the correct format"
            print line
            answer = raw_input("continue?")
            if (answer.lower.find('y') >= 0):
                continue
            else:
                sys.exit(1)

        #Get the title
        title = tokens[2]
        if (token_count > 4):
            for count in range(3, (token_count - 1)):
                title = title + tokens[count]

        #Make sure that we have the correct value
        if (title.find("@en") < 0):
            print "ERROR: Invalid tokens"
            print line
            answer = raw_input("continue?")
            if (answer.lower.find('y') >= 0):
                continue
            else:
                sys.exit(1)

        #Remove all unnecessary strings
        title = title.strip("@en")
        title = title.strip("\"")
        #Make it lower so it is case-insensitive
        title = title.lower()

        page = tokens[0]
        titles[title] = page

    fp.close()
    return titles


class whereClause():
    def __init__(self, subject, predicate, obj):
        self.subject = subject
        self.predicate = predicate
        self.object = obj

    def getString(self):
        return self.subject + " " + self.predicate + " " + self.object

class Query():
    def __init__(self):
        self.prefix = {}
        self.select = []
        self.where = []
        self.filter = ""

    def addPrefix(self, prefixString, prefixUrl):
        if (not self.prefix.has_key(prefixString)):
            self.prefix[prefixString] = prefixUrl

    def addSelect(self, var):
        if (not (var in self.select)):
            self.select.append(var)

    def addWhere(self, sub, pred, obj):
        self.where.append(whereClause(sub, pred, obj))

    def addFilter(self, string):
        self.filter = string

    def getQueryString(self):
        string = ""
        for eachPrefixString in self.prefix.keys():
            prefixString = "PREFIX " + eachPrefixString + ": "
            prefixString = prefixString + "<" + self.prefix[eachPrefixString] +">"
            string = string + prefixString + "\n"

        selectString = "SELECT "
        for eachSelectVar in self.select:
            selectString = selectString + eachSelectVar + ","
        string = string + selectString[:-1]
        string = string + "\n"

        whereString = "WHERE {\n"
        for eachWhere in self.where:
            whereString = whereString + "\t" + eachWhere.getString() + " .\n"
        if (len(self.filter) > 0):
            whereString = whereString + "\tFILTER " + self.filter + "\n"
        whereString = whereString + "}"
        string = string + whereString

        return string

def DBPediaQuery(query):
    sparql = SPARQLWrapper("http://dbpedia.org/sparql")
    sparql.setReturnFormat(JSON)
    sparql.setQuery(query)
    try:
        results = sparql.query()
        return results.convert()
    except Exception as e:
        print "ERROR: Exception" + str(e)
    return None